package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Department;
import cn.wolfcode.mapper.DepartmentMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.DepartmentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 部门业务层
 *
 * @author 杨兴健
 * @Date 2020/7/9 10:34
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    private DepartmentMapper mapper;

    /**
     * 根据查询条件查询部门并封装成ResultSet对象
     *
     * @param qo
     * @return
     */
    @Override
    public PageInfo<Department> selectAllByQO(QueryObject qo) {

//        用pageHelper插件开始分页
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Department> departments = mapper.selectAllByQO(qo);
//        结果集封装成PageInfo
        PageInfo<Department> pageInfo = new PageInfo<>(departments);

        return pageInfo;
    }

    /**
     * 根据id查询部门
     *
     * @param id
     * @return
     */
    @Override
    public Department selectById(Long id) {
        Department department = mapper.selectById(id);
        return department;
    }


    /**
     * 根据id删除部门数据
     *
     * @param id
     */
    @Override
    public void delete(Long id) {
        if (id != null) {
            mapper.delete(id);
        }
    }

    /**
     * 查询所有的部门
     *
     * @return
     */
    @Override
    public List<Department> selectAll() {
        return mapper.selectAll();
    }

    /**
     * 添加或保存
     *
     * @param department
     */
    @Override
    public void saveOrUpdate(Department department) {
        if (department == null) {
            throw new RuntimeException("数据为空");
        }
        if (!StringUtils.hasText(department.getName())) {
            throw new RuntimeException("部门名称不能为空");
        }
        if (!StringUtils.hasText(department.getSn())) {
            throw new RuntimeException("部门编号不能为空");
        }

        if (department.getId() != null) {
            mapper.update(department);
        } else {
            mapper.insert(department);
        }
    }
}
